<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'btn:bom:pmMaterial:update'"
    @register="registerDrawer"
    @ok="handleUpdate"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <template #footer>
      <a-button type="primary" @click="handleSubmit()" v-auth="'btn:bom:pmMaterial:fp'">
        <Icon icon="ant-design:check-outlined" /> {{ t('确认分配') }}
      </a-button>
    </template>
    <BasicForm @register="registerForm">
      <template #fpDataChildList>
        <BasicTable @register="registerfpDataChildTable" @row-click="handlefpDataChildRowClick" />
        <a-button class="mt-2" @click="handlefpDataChildAdd" v-auth="'material:bom:pmMaterial:fp'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialBomPmMaterialForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmMaterial,
    pmMateriallUpdateQty,
    pmMateriallAllot,
  } from '/@/api/material/bom/pmMaterial';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.bom.pmMaterial');
  const { showMessage } = useMessage();
  const record = ref<PmMaterial>({} as PmMaterial);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    //value: record.value.isNewRecord ? t('新增材料清单') : t('编辑材料清单'),
    value: record.value.isNewRecord ? t('发起材料分配') : t('材料分配'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'fpDataChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'fpDataChildList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerfpDataChildTable, fpDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlefpDataChildDelete.bind(this, record),
          },
          auth: 'btn:bom:pmMaterial:fp',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setfpDataChildTableData(_res: Recordable) {
    fpDataChildTable.setColumns([
      {
        title: t('项目编号'),
        dataIndex: 'projectno',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('项目名称'),
        dataIndex: 'projectname',
        width: 300,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('材料编码'),
        dataIndex: 'mcode',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('材料名称'),
        dataIndex: 'mname',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'mstd',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('单位'),
        dataIndex: 'unit',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('用量'),
        dataIndex: 'num',
        width: 80,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('累计请购'),
        dataIndex: 'sumPuQty',
        width: 100,
        align: 'right',
        editRow: false,
        editComponent: 'InputNumber',
        editRule: false,
      },
      {
        title: t('累计库领'),
        dataIndex: 'sumStQty',
        width: 100,
        align: 'right',
        editRow: false,
        editComponent: 'InputNumber',
        editRule: false,
      },
      {
        title: t('请购量'),
        dataIndex: 'puQty',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        fixed: 'right',
      },
      {
        title: t('库领量'),
        dataIndex: 'stQty',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        fixed: 'right',
      },
    ]);
    fpDataChildTable.setTableData(record.value.fpDataChildList || []);
  }

  function handlefpDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlefpDataChildAdd() {
    fpDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handlefpDataChildDelete(record: Recordable) {
    fpDataChildTable.deleteTableDataRecord(record);
  }

  async function getfpDataChildList() {
    let fpDataChildListValid = true;
    let fpDataChildList: Recordable[] = [];
    for (const record of fpDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        fpDataChildListValid = false;
      }
      fpDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of fpDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      fpDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!fpDataChildListValid) {
      throw { errorFields: [{ name: ['fpDataChildList'] }] };
    }
    return fpDataChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    // const res = await pmMaterialForm(data);
    // record.value = (res.pmMaterial || {}) as PmMaterial;
    record.value = data
    record.value.__t = new Date().getTime();
    record.value.fpDataChildList = data.list;
    setFieldsValue(record.value);
    record.value.fpDataChildList = record.value.fpDataChildList.map((e) => {
      return {
        projectno: e.pcode,
        projectname: e.name,
        ...e,
      };
    });
    setfpDataChildTableData(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        fpStatus: record.value.fpStatus?record.value.fpStatus:''
      };
      data.materialFpList = await getfpDataChildList();
      data.fpStatus = record.value.fpStatus?record.value.fpStatus:''
      // console.log('submit', params, data, record);
      const res = await pmMateriallAllot(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleUpdate() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      console.log(record.value);
      data.materialFpList = await getfpDataChildList();
      // console.log('submit', params, data, record);
      const res = await pmMateriallUpdateQty(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
